#!/usr/bin/env python
#

import xml.dom.minidom


def addDomNode( parent_node, nodename, value=None, cdata=False ) : 

    doc = xml.dom.minidom.Document()

    child = doc.createElement( nodename )

    if ( None != value ):
        if ( cdata ):
            TextNode = doc.createCDATASection( value )
        else:
            TextNode = doc.createTextNode( value )
        child.appendChild( TextNode )


    return parent_node.appendChild( child )
    #### addDomNode()

def addDomNodeText( node, value=None, cdata=False ) : 

    doc = xml.dom.minidom.Document()

    if ( None != value ):
        if ( cdata ):
            TextNode = doc.createCDATASection( value )
        else:
            TextNode = doc.createTextNode( value )
        node.appendChild( TextNode )

    #### addDomNodeText()


def getChildren(node_parent, tag_child) :
    try :
        children = node_parent.getElementsByTagName( tag_child )
    except :
        children = []

    return children
    ## getChildren()


def getChildrenByPath(node_root, path) :
    children = []
    if not path : 
        return children

    tags = path.strip().split('/')
    node = node_root
    walk = 0 
    for tag in tags :
        walk += 1
        if not tag :
            continue
        children = getChildren(node, tag)
        if not children :
            raise RuntimeError, 'Invalid XML path: "%s"' % '/'.join(tags[:walk])

        node = children[0]

    return children
    ## getChildrenByPath()


def getNodeText(node) :
    text = ''
    for subnode in node.childNodes :
        if subnode.nodeType in ( xml.dom.Node.TEXT_NODE, xml.dom.Node.CDATA_SECTION_NODE):
            text = text + subnode.data

    return  text
    ## getNodetext()


if  __name__ == '__main__' :
    
    dom_root = xml.dom.minidom.getDOMImplementation().createDocument( None, 'document', None )

    xml_str = dom_root.toxml()
    print xml_str
    
    ###################################################################

    dom = xml.dom.minidom.parseString( xml_str )

    node_root = dom.getElementsByTagName( 'document' )[0]

    node_key = addDomNode( node_root, 'key' )
    addDomNode( node_key, 'url', 'sample url', cdata=True )
    addDomNode( node_key, 'md5', 'sample md5', cdata=False )

    addDomNode( node_key, 'url', 'sample url II', cdata=True )
    addDomNode( node_key, 'md5', 'sample md5 II', cdata=False )

    xml_str = dom.toxml()
    print xml_str
    
    
    ###################################################################

    dom = xml.dom.minidom.parseString( xml_str )

    node_root = dom.getElementsByTagName( 'document' )[0]

    node_keys = getChildrenByPath( dom, 'document/key' )

    for node_key in node_keys :
        node_md5s = node_key.getElementsByTagName( 'md5' )
        for node_md5 in node_md5s :
            for subnode in node_md5.childNodes :
                node_md5.removeChild( subnode )

    xml_str = dom.toxml()
    print xml_str
    
    i = 0

    for node_key in node_keys :
        node_md5s = node_key.getElementsByTagName( 'md5' )
        for node_md5 in node_md5s :
            i += 1
            addDomNodeText( node_md5, 'MD5 %04d' % i, cdata=True )

    xml_str = dom.toxml()
    print xml_str
    
    
    ###################################################################

    dom = xml.dom.minidom.parseString( xml_str )

    print dom.childNodes
    print dom.nodeName

    node_root = dom.firstChild
    print node_root.nodeName

    # get node ROOT
    root = dom.documentElement
    print root.nodeName
    print root.attributes
    
